<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select v-model="listQuery.query.suiteId" placeholder="请选择套件名称" class="filter-item" clearable filterable @change="filter">
        <el-option
          v-for="item in testSuiteList"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        />
      </el-select>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-search" @click="filter">搜索</el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column prop="id" align="center" label="结果Id" width="95" sortable>
        <template v-slot="{row}">
          {{ row.id }}
        </template>
      </el-table-column>
      <el-table-column prop="name" label="套件名称" sortable>
        <template v-slot="{row}">
          {{ row.suiteName }}
        </template>
      </el-table-column>
      <el-table-column align="center" :label="caseType === getCatalogTypeValue('接口测试用例') ? '保留' : '基线'" width="120">
        <template v-slot="{row}">
          <i v-if="row.reserved || row.baseLine" class="el-icon-check" style="color: green; font-size: 24px; font-weight: bold;" />
        </template>
      </el-table-column>
      <el-table-column prop="name" align="center" label="执行用户" width="200">
        <template v-slot="{row}">
          {{ row.runUser }}
        </template>
      </el-table-column>
      <el-table-column prop="name" align="center" label="运行状态" width="150">
        <template v-slot="{row}">
          <el-tag style="margin-left: 0px" size="small" :type="getRunStatusName(row.status)==='通过'?'success':getRunStatusName(row.status)==='警告' || getRunStatusName(row.status)==='中断' ?'warning':getRunStatusName(row.status) === '失败'? 'danger' : 'info'">
            <i v-if="getRunStatusName(row.status) === '运行中'" class="el-icon-loading" style="margin-right: 5px;" />
            {{ getRunStatusName(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="created_at" label="创建时间" width="140px">
        <template v-slot="{row}">
          <span> {{ row.createdAt | parseTime('{y}-{m}-{d} {h}:{i}') }} </span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="310px">
        <template v-slot="{row}">
          <div style="text-align: center">
            <el-button size="mini" icon="el-icon-tickets" @click="showReportDetails(row)">查看报告</el-button>
            <el-button v-if="caseType === getCatalogTypeValue('接口测试用例') && !row.reserved" type="primary" size="mini" icon="el-icon-lock" @click="updateReserved(row)">设为保留</el-button>
            <el-button v-else-if="caseType === getCatalogTypeValue('接口测试用例') && row.reserved" type="primary" size="mini" icon="el-icon-key" @click="updateReserved(row)">取消保留</el-button>
            <el-button v-else-if="caseType === getCatalogTypeValue('性能测试用例') && !row.baseLine" type="primary" size="mini" icon="el-icon-lock" @click="updateBaseLine(row)">设为基线</el-button>
            <el-button v-else-if="caseType === getCatalogTypeValue('性能测试用例') && row.baseLine" type="primary" size="mini" icon="el-icon-key" @click="updateBaseLine(row)">取消基线</el-button>
            <el-button :disabled="row.status > getRunStatusValue('运行中') || row.suiteId === -9999" type="danger" size="mini" @click="forceStopSuite(row)"><svg-icon icon-class="stop" />中断</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="listQuery.totalRecords>0" :total="listQuery.totalRecords" :page.sync="listQuery.pageNum" :limit.sync="listQuery.pageSize" @pagination="fetchData" />
  </div>
</template>

<script>
import { list as testResultList } from '@/api/functional_test/automated_test/test_result'
import { perfTestResultList } from '@/api/performance_test/perf_test_result'
import Pagination from '@/components/Pagination'
import { getRunStatusName, getRunStatusValue } from '@/enum/runStatus.js'
import { forceStopSuite as funcForceStopSuite, funcUpdateReserved } from '@/api/functional_test/test_case_manage/test_suite'
import { selectAll as testSuiteSelectAll } from '@/api/functional_test/test_case_manage/test_suite'
import { perfTestSuiteListAll, perfForceStop, perfUpdateBaseLine } from '@/api/performance_test/perf_test_suite'
import { getCatalogTypeValue } from '@/enum/catalogType'

export default {
  components: { Pagination },
  props: {
    caseType: {
      type: Number,
      default: 1
    }
  },
  data() {
    return {
      list: null,
      listLoading: true,
      listQuery: {
        pageNum: 1,
        pageSize: 10,
        totalRecords: 0,
        orders: undefined,
        query: {
          caseType: this.caseType, // 元素类型（caseType=功能测试用例 CatalogType=1，caseType=接口测试用例 CatalogType=3, caseType=公共步骤 CatalogType=4，caseType=性能测试 CatalogType=5）
          projectId: this.$route.query.projectId || this.$store.getters.projectId,
          suiteId: this.$route.query.suiteId
        }
      },
      testSuiteList: [], // 套件列表
      temp: {
        id: undefined,
        name: ''
      }
    }
  },
  created() {
    this.fetchData()
    const projectId = this.listQuery.query.projectId
    if (this.caseType === getCatalogTypeValue('接口测试用例')) {
      testSuiteSelectAll({
        projectId: projectId,
        caseType: this.caseType // 元素类型（caseType=功能测试用例 CatalogType=1，caseType=接口测试用例 CatalogType=3, caseType=公共步骤 CatalogType=4，caseType=性能测试 CatalogType=5）
      }).then(response => {
        this.testSuiteList = response.data
      })
    } else if (this.caseType === getCatalogTypeValue('性能测试用例')) {
      perfTestSuiteListAll(projectId).then(response => {
        this.testSuiteList = response.data
      })
    }
  },
  methods: {
    getRunStatusName,
    getRunStatusValue,
    getCatalogTypeValue,
    fetchData() {
      this.listLoading = true
      if (this.caseType === getCatalogTypeValue('接口测试用例')) {
        testResultList(this.listQuery).then(response => {
          this.list = response.data.list
          this.listQuery.totalRecords = response.data.page.totalRecords
          this.listLoading = false
        })
      } else if (this.caseType === getCatalogTypeValue('性能测试用例')) {
        perfTestResultList(this.listQuery).then(response => {
          this.list = response.data.list
          this.listQuery.totalRecords = response.data.page.totalRecords
          this.listLoading = false
        })
      }
    },
    filter() {
      this.listQuery.pageNum = 1
      this.fetchData()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        name: ''
      }
    },
    showReportDetails(row) {
      if (this.caseType === getCatalogTypeValue('接口测试用例')) {
        this.$router.push({
          path: '/functional_test/result_detail',
          query: { resultId: row.id }
        })
      } else if (this.caseType === getCatalogTypeValue('性能测试用例')) {
        this.$router.push({
          path: '/performance_test/perf_result_detail',
          query: { resultId: row.id }
        })
      }
    },
    // 点击 设为、去掉 保留 按钮
    updateReserved(row) {
      let msg = ''
      if (row.reserved) {
        msg = '是否将此测试报告 取消保留？'
      } else {
        msg = '是否将此测试报告 设为保留？'
      }
      this.$confirm(msg, '提示', {
        confirmButtonText: '是',
        cancelButtonText: '否',
        type: 'warning'
      }).then(() => {
        funcUpdateReserved(row.id).then(response => {
          if (response.data.reserved) {
            row.reserved = response.data.reserved
            this.$message({ message: '此测试报告 设为保留 成功!', type: 'success' })
          } else {
            row.reserved = response.data.reserved
            this.$message({ message: '此测试报告 取消保留 成功!', type: 'success' })
          }
        })
      }).catch(() => {
      })
    },
    // 点击 设为、取消 基线 按钮
    updateBaseLine(row) {
      let msg = ''
      if (row.baseLine) {
        msg = '是否将此测试报告 取消基线？'
      } else {
        msg = '是否将此测试报告 设为基线？'
      }
      this.$confirm(msg, '提示', {
        confirmButtonText: '是',
        cancelButtonText: '否',
        type: 'warning'
      }).then(() => {
        perfUpdateBaseLine(row.id).then(response => {
          if (response.data.baseLine) {
            for (const rowData of this.list) {
              if (rowData.suiteId === row.suiteId && rowData.baseLine) {
                rowData.baseLine = false
              }
            }
            row.baseLine = response.data.baseLine
            this.$message({ message: '此测试报告 设为基线 成功!', type: 'success' })
          } else {
            row.baseLine = response.data.baseLine
            this.$message({ message: '此测试报告 取消基线 成功!', type: 'success' })
          }
        })
      }).catch(() => {
      })
    },
    // 点击 中断 按钮
    forceStopSuite(row, index) {
      this.$confirm('是否强制停止本次运行?', '提示', {
        confirmButtonText: '是',
        cancelButtonText: '否',
        type: 'warning'
      }).then(() => {
        if (this.caseType === getCatalogTypeValue('接口测试用例')) {
          funcForceStopSuite(row.id).then(response => {
            row.status = getRunStatusValue('中断')
            this.$message({ message: '停止运行成功!', type: 'success' })
          })
        } else if (this.caseType === getCatalogTypeValue('性能测试用例')) {
          perfForceStop(row.id).then(response => {
            row.status = getRunStatusValue('中断')
            this.$message({ message: '停止运行成功!', type: 'success' })
          })
        }
      })
    }
  }
}
</script>
